
use -- the proper database below according to the current environment
	Events_Temp 
 -- Test_Events_Temp
 -- Live_Events_Temp

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.PublishedIncidents ADD
	ExternalUrl nvarchar(MAX) NULL
GO
ALTER TABLE dbo.PublishedIncidents SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

GO 
/****** Object:  StoredProcedure [dbo].[spGetIncidentsByCompanyIds]    Script Date: 12/8/2017 3:08:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER PROCEDURE [dbo].[spGetIncidentsByCompanyIds]
	@CompanyIds NVARCHAR(MAX)
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @XML XML
	SET @XML = CONVERT(XML, @CompanyIds, 1)

	DECLARE @SelectedCompanies TABLE
	(
		Id uniqueidentifier
	)
	INSERT INTO @SelectedCompanies
	SELECT TID.id.value('.','uniqueidentifier') AS Id
	FROM @XML.nodes('/CompanyIds') AS T(c) outer apply T.c.nodes('Id') as TID(id)

	SELECT PublishedIncidents.[Id]
		  ,[CompanyId]
		  ,[EventIndicatorId]
		  ,[EventIndicatorName]
		  ,[IncidentId]
		  ,[Type]
		  ,[Name]
		  ,[Summary]
		  ,[Analysis]
		  ,[MainTag]
		  ,[HasSupplyChainSpecialTag]
		  ,[Source]
		  ,[IncidentDate]
		  ,[LocationAddress]
		  ,[LocationLatitude]
		  ,[LocationLongitude]
		  ,[ImpactScore]
		  ,[RiskScore]
		  ,[LastUpdated]
		  ,[Timestamp]
		  ,ROW_NUMBER() OVER(PARTITION BY [IncidentId],CompanyId ORDER BY (Select Max(v) from (VALUES([RiskScore]),([ImpactScore])) as value(v)) DESC, LastUpdated DESC) AS RowNo
		  ,[ExternalUrl]
	FROM [dbo].[PublishedIncidents] AS PublishedIncidents
	INNER JOIN @SelectedCompanies AS SelectedCompanies ON SelectedCompanies.Id = PublishedIncidents.CompanyId
	 
END

GO 

declare @eventsDB sysname = LEFT(DB_NAME(), LEN(DB_NAME()) - 5) -- drop the suffix _Temp

exec('update PublishedIncidents set ExternalUrl = case when na.ExternalUrl like ''http%'' and na.LexisNexis is null then na.ExternalUrl else null end 
		from PublishedIncidents pi 
		join ' + @eventsDB + '.dbo.Incidents i on pi.Id = i.Id 
		join ' + @eventsDB + '.dbo.NewsArticles na on i.NewsArticleId = na.Id')